﻿// -----------------------------------------------------------------------
// <copyright file="LocatorServiceHost.cs" company="Henadzi Sabaleuski.">
// Copyright (c) Henadzi Sabaleuski. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace OCM.Enterprise.OCR.Utilities.Unity
{
	#region Usings

	using System;
	using System.ServiceModel;

	using HSabaleuski.Utilities.Diagnostics;
	using Microsoft.Practices.ServiceLocation;

	#endregion

	/// <summary>
	/// Represents a <see cref="ServiceHost"/> which uses Service Locator pattern for the Dependency Injection purposes.
	/// </summary>
	public class LocatorServiceHost : ServiceHost
	{
		#region Private Fields

		/// <summary>
		/// The <see cref="IServiceLocator"/> field which used for Dependency Injection purposes.
		/// </summary>
		private readonly IServiceLocator serviceLocator;

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="LocatorServiceHost"/> class.
		/// </summary>
		/// <param name="serviceLocator">The service locator.</param>
		/// <param name="serviceType">Type of the service.</param>
		/// <param name="baseAddresses">The base addresses.</param>
		public LocatorServiceHost(IServiceLocator serviceLocator, Type serviceType, params Uri[] baseAddresses)
			: base(serviceType, baseAddresses)
		{
			Guard.VerifyNullable(serviceLocator);

			this.serviceLocator = serviceLocator;
		}

		#endregion

		#region ServiceHost Overrides

		/// <summary>
		/// Invoked during the transition of a communication object into the opening state.
		/// </summary>
		protected override void OnOpening()
		{
			if (this.Description != null &&
				this.Description.Behaviors != null &&
				this.Description.Behaviors.Find<LocatorServiceBehavior>() == null)
			{
				this.Description.Behaviors.Add(new LocatorServiceBehavior(this.serviceLocator));
			}

			base.OnOpening();
		}

		#endregion
	}
}